package com.sheng.leetcode.year2022.swordfingeroffer.day19;

import org.junit.Test;

/**
 * @author liusheng
 * @date 2022/09/19
 *<p>
 * 剑指 Offer 68 - II. 二叉树的最近公共祖先<p>
 *<p>
 * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。<p>
 * 百度百科中最近公共祖先的定义为：“对于有根树 T 的两个结点 p、q，最近公共祖先表示为一个结点 x，<p>
 * 满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）。”<p>
 * 例如，给定如下二叉树: root =[3,5,1,6,2,0,8,null,null,7,4]<p>
 *<p>
 * 示例 1:<p>
 * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1<p>
 * 输出: 3<p>
 * 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。<p>
 * <p>
 * 示例2:<p>
 * 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4<p>
 * 输出: 5<p>
 * 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。<p>
 *<p>
 * 说明:<p>
 *<p>
 * 所有节点的值都是唯一的。<p>
 * p、q 为不同节点且均存在于给定的二叉树中。<p>
 * 注意：本题与主站 236 题相同：<a href="https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/">...</a><p>
 *<p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/er-cha-shu-de-zui-jin-gong-gong-zu-xian-lcof">...</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class Sword0068Two {

    @Test
    public void test01() {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(5);
        TreeNode treeNode = new TreeNode(2);
        treeNode.left =  new TreeNode(7);
        treeNode.right =  new TreeNode(4);
        left.left = new TreeNode(6);
        left.right = treeNode;
        TreeNode right = new TreeNode(1);
        right.left = new TreeNode(0);
        right.right = new TreeNode(8);
        root.left = left;
        root.right = right;
        TreeNode p = new TreeNode(5);
//        TreeNode q = new TreeNode(1);
        TreeNode q = new TreeNode(4);
        TreeNode node = new Solution68Two().lowestCommonAncestor(root, p, q);
        System.out.println(node);
    }
}
class Solution68Two {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root.val == p.val || root.val == q.val) {
            return root;
        }
        // 后续遍历
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        if (left == null && right != null) {
            return right;
        } else {
            return left;
        }
    }
}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
